<?php
error_reporting(E_ALL ^ E_NOTICE);

$fileName = './BirdLife_Checklist_Version_3.csv';

$type = trim($_REQUEST['type']);
$value = trim($_REQUEST['value']);

$indexArray = array('family' => 0, 'common' =>1, 'scientificName' => 2, 'iucn' => 5);
$iucnArray = array('CR', 'EN', 'NT', 'VU');

$ar = parseData($type, $value);

function parseData($type, $value='all') {
	global $fileName, $indexArray, $iucnArray;
	$value = (trim($value) != '') ? $value : 'all';
	if(!in_array($type,$indexArray)) return false;
	$typeIndex = $indexArray[$type];
	$output = array();
	$dataArray = array();
	$op = array();
	$tmp = '';
	$tmpArray = array();
	$sortArray = array();
	$counter = 0;
	$dataFlag = false;
	if (($handle = fopen($fileName, 'r')) !== FALSE) {

	while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
		$dataArray[] = $data;
	}
	array_shift($dataArray);
	$dataFlag = (is_array($dataArray) && count($dataArray)) ? true : false;

	if($value == 'all') {
		switch($type) {
			case 'family':
				if($dataFlag) {
				foreach($dataArray as $data) {
					if($tmp != trim($data[$typeIndex]) && !in_array(trim($data[$typeIndex]),$tmpArray) && trim($data[$typeIndex]) != '') {
						$tmp = trim($data[$typeIndex]);
						$tmpArray[] = trim($data[$typeIndex]);
						$output[] = $data[$typeIndex];
					}
				}
				@sort($output);
				if(is_array($output) && count($output)) {
					foreach($output as &$op) {
						$op = array('text' => $op,'id' => $op,'leaf' => false);
					}
				}
				$ar = array('success' => true, 'data' => $output);
				}
				break;
			case 'iucn':
				if(is_array($iucnArray) && count($iucnArray)) {
					foreach($iucnArray as $iucn) {
						$output[] = array('text' => $iucn,'id' => $iucn,'leaf' => false);
					}
				$ar = array('success' => true, 'data' => $output);
				}
				break;
		} # switch
	} else {
		if($dataFlag) {
			foreach($dataArray as $data) {
				if(trim($data[$typeIndex]) == $value) {
					$sortArray[$data[2]] = array('text' => $data[2],'id' => $data[6],'leaf' => true, 'commonName' => $data[1], 'iucn' => $data[5], 'family' => $data[0], 'checked' => false);
				}
			}
			@ksort($sortArray);
			$sortArray = @array_values($sortArray);

			if(is_array($sortArray) && count($sortArray)) {
				foreach($sortArray as $op) {
					$output[] = $op;
				}
			}
		$ar = array('success' => true, 'data' => $output);
		}
	} # value 'all'
		fclose($handle);
	} # file handle

	return $ar;
} # function

if(!count($ar)) $ar = array('success' => true);

header('Content-type: application/json');
echo json_encode($ar);

?>